package com.luochq.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ReactorBossServer {
    public static void main(String[] args) throws IOException {
        log.debug("boss thread run ... ");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8888));
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
//        ByteBuffer buffer = ByteBuffer.allocate(10);
//        buffer.capacity();
//        Worker worker = new Worker("worker");
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i ++ ) {
            workers[i] = new Worker("worker-" + i + 1);
        }
        AtomicInteger id = new AtomicInteger();
        while (true) {
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("boss invoke worker register ...");
                    workers[id.incrementAndGet() % workers.length].register(sc);
                    log.debug("boss invoked worker register ...");
                }
            }
        }
    }
}
